package udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
 
public class EchoServer01 {
    private DatagramSocket socket;
    
    public EchoServer01(int port ) throws Exception {
        socket=new DatagramSocket(port);
    }
    
    public void start() throws Exception{
        System.out.println("服务器启动");
        while(true){
            //创建空白的DatagramPacket对象的reqScoket用来接收客户端请求
            DatagramPacket reqSocket=new DatagramPacket(new byte[4096],4096);
            //用recive方法读取数据
            socket.receive(reqSocket);
            //解析成字符串
            String resPacket=new String(reqSocket.getData(),reqSocket.getOffset(),reqSocket.getLength());
            //根据请求返回响应
            String ret=process(resPacket);
            //用DatagramPacket封装响应内容
            DatagramPacket respPacket=new DatagramPacket(ret.getBytes(),
            ret.getBytes().length,reqSocket.getSocketAddress());
            //用send方法发送响应    
            socket.send(respPacket);
            //打印日志
            System.out.printf("[%s:%d] req:%s resp: %s\n  ",
                reqSocket.getAddress(),reqSocket.getPort(),resPacket,ret);
        }
    }

    public String process(String resPacket){
        return resPacket;
    }



    public static void main(String[] args) throws Exception {
        EchoServer01 rServer01=new EchoServer01(9090);
        rServer01.start();
    }
}
